package com.tjbank.cssys.tools.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Copyright © 天阳宏业科技股份有限公司 - All Rights Reserved
 *
 * @description: 为了与自定义的Key匹配,增加该Handler类.
 * @author: <a href="mailto:guzheng01@tansun.com.cn>Joey Gu</a>
 * @date: 2020-05-11 15:13
 **/
@Slf4j
public class RedisCacheManagerHandler extends RedisCacheManager {

    @Value("${spring.application.name:unnamespace}")
    private String cacheNamespace;

    public RedisCacheManagerHandler(RedisCacheWriter cacheWriter,
                                    RedisCacheConfiguration defaultCacheConfiguration,
                                    Map<String, RedisCacheConfiguration> initialCacheConfigurations) {
        super(cacheWriter, defaultCacheConfiguration, initialCacheConfigurations);
    }

    @Override
    public Cache getCache(@Nullable String name) {
        // 根据规范判断是否找到已定义的缓存信息
        if (!StringUtils.isEmpty(name) && super.getCacheConfigurations().containsKey(cacheNamespace.concat(":").concat(name))) {
           name = cacheNamespace.concat(":").concat(name);
        }
        return super.getCache(name);
    }

    /**
     * 还可利用此处调整ttl,以满足自定义ttl时间.
     * <p />
     * <pre>
     *    String[] array = org.springframework.util.StringUtils.delimitedListToStringArray(name, "#");
     *    name = array[0];
     *    // 解析TTL
     *    if (array.length > 1) {
     *      long ttl = Long.parseLong(array[1]);
     *      // 注意单位此处用的是秒，而非毫秒
     *      cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
     *     }
     * </pre>
     */
    @Override
    protected RedisCache createRedisCache(String name, @Nullable RedisCacheConfiguration cacheConfig) {
        if (log.isDebugEnabled()) {
        }
        return super.createRedisCache(name, cacheConfig);
    }
}
